package com.example.springbootaop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class TestAspect {

    private final static Logger logger= LoggerFactory.getLogger(TestAspect.class);
    /**
     * 指定切点
     */
    @Pointcut("execution(public * com.example.springbootaop.controller.TestController.*(..))")
    public void webLog(){}

    /**
     * 前置通知：方法调用前被调用
     * @param joinPoint
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint){
        logger.info("doBefore 方法执行之前");

        Signature signature = joinPoint.getSignature();
        //获取request
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        logger.info("url={}",request.getRequestURI());
        //method
        logger.info("method={}",request.getMethod());
        //ip
        logger.info("ip={}",request.getRemoteAddr());
        //代理类
        logger.info("代理类："+signature.getDeclaringTypeName());
        //代理类法
        logger.info("代理类方法:"+signature.getName());
        //请求参数名称
        MethodSignature methodSignature = (MethodSignature) signature;
        String[] parameterNames = methodSignature.getParameterNames();
        logger.info("parameterNames={}", Arrays.toString(parameterNames));
        //请求参数值
        logger.info("parameterValues={}", Arrays.toString(joinPoint.getArgs()));
    }
    /**
     * 后置通知：方法调用后被调用
     */
    @After("webLog()")
    public void doAfter(){
        logger.info("doAfter：方法执行之后");
    }


    /**
     * 获取返回值
     * @param object
     */
    @AfterReturning(returning = "object",pointcut = "webLog()")
    public void doAfterReturning(Object object){
        logger.info("response={}",object);
    }
}
